/**
 * Created by midori on 2015/12/7.
 */
(function(){
    var module = angular.module("directives.TestSummary",[
        'restangular',
        "services.TestService",
        "services.utils.RestAngularHandler",
        "services.Utils"
    ]);
    module.directive("acTestSummary", ['TestService',
        'Restangular',
        'RestAngularHandlerFactory',
        "$http",
        "$templateCache",
        "$compile",
        "utils",

        function(testService, restangular, restAngularHandlerFactory, $http, $templateCache, $compile, utils){
            var _cached_templates = {};
            return {
                restrict: "A",
                replace: false,
                transclude: false,
                templateUrl: "testsummary/list-waiting",
                scope: {
                    testId: "=acTestId",
                    testIds: "=acTestIds"
                },
                link: function(scope, elem, attr){

                    var currentData, cachedTooltip;

                    scope.rest = {};
                    scope.rest.getTestSummary = {};
                    scope.rest.getTestConfiguration = {};
                    scope.rest.getLatestTestRunProgress = {};
                    scope.rest.getTargetAppName = {};
                    scope.rest.deleteTest = {};
                    scope.rest.recheckLatestTestRun = {};
                    scope.rest.cancelTest = {};
                    scope.rest.startTestRun = {};

                    scope.testSummaryData = {};
                    scope.testProgress = {};

                    scope.getTemplate = function(viewName){
                        var templateName = "/app/templates/test-summary/" + viewName;
                        return $templateCache.get(templateName);
                    };

                    scope.testFailed = function() {
                        return scope.testSummaryData.lastRunStatus === "Failed" || scope.testSummaryData.lastRunStatus === "BUILD_FAILED" ;
                    };
                    scope.testCanceled = function() {
                        return scope.testSummaryData.lastRunStatus === "Canceling";
                    };
                    scope.testDone = function() {
                        return scope.testSummaryData.lastRunStatus === "Done" || scope.testSummaryData.lastRunStatus === "Report created" ;
                    };
                    scope.testStatusUndefined = function() {
                        return !((scope.testSummaryData.lastRunStatus != null) && scope.testSummaryData.lastRunStatus.length !== 0);
                    };
                    scope.testRunning = function() {
                        return !(scope.testFailed() || scope.testCanceled() || scope.testDone() || scope.testStatusUndefined());
                    };

                    scope.toNiceTimeString = function(timeAsDateFromDB) {
                        return utils.toTimeZoneAwareTimeString(parseInt(timeAsDateFromDB), scope.user);
                    };

                    scope.hasTestRunProgress = function() {
                        return scope.testProgress != null;
                    };

                    scope.getTestRunProgress = function(testId) {
                        var newTestRestHandler;
                        newTestRestHandler = restAngularHandlerFactory.createAndStart(scope.rest.getLatestTestRunProgress);
                        return restangular.one("test-plan", testId).one("lastrun/progress").get()
                            .then(newTestRestHandler.getSuccessCallback(function (testRunProgress) {
                                // console.log(testRunProgress);
                                return scope.testProgress = testRunProgress;
                            }), newTestRestHandler.getErrorCallback(function (result) {
                                //TODO: display error message
                                console.log("error");
                            }));
                    };

                    currentData = void 0; cachedTooltip = void 0;
                    scope.computeLastRunTooltip = function(data) {
                        var duration, res, timeDiff;
                        if (data == null) {
                            return "Data pending...";
                        } else {
                            if (data === currentData) {
                                return cachedTooltip;
                            }
                            res = scope.computeRunningTestTooltip(data);
                            res += "<br>";
                            res += "Last run: " + scope.toNiceTimeString(data.lastRunStartTime);
                            res += "<br>";
                            timeDiff = new Date(data.optLastRunEndTime) - new Date(data.lastRunStartTime);
                            duration = Math.round(timeDiff / 1000);
                            if (isNaN(duration)) {
                                res += "<br>- This test was not completed -";
                            } else {
                                res += "Duration: " + Math.round(timeDiff / 1000) + " seconds";
                            }
                            currentData = data;
                            return cachedTooltip = res;
                        }
                    };
                    scope.computeRunningTestTooltip = function(data) {
                        if ((data != null)) {
                            return "Created: " + scope.toNiceTimeString(data.createTime);
                        } else {
                            return "Creation time pending...";
                        }
                    };

                    scope.updateTestSummary = function(){
                        return testService.getTestSummary(scope.testId).then(function(newTestSummaryData){
                            return scope.testSummaryData = newTestSummaryData;
                        }).then(function(){
                            return scope.getTestRunProgress(scope.testId);
                        });
                    };
                    
                    // scope.getAppName = function(apkID){
                    //     var newTestRestHandler;
                    //     newTestRestHandler = restAngularHandlerFactory.createAndStart(scope.rest.getTargetAppName);
                    //     return restangular.one("target-apk", apkID).get()
                    //         .then(newTestRestHandler.getSuccessCallback(function (result) {
                    //             // console.log(result);
                    //             return result.name;
                    //         }), newTestRestHandler.getErrorCallback(function (result) {
                    //             //TODO: display error message
                    //             console.log("error");
                    //         }));
                    // };
                    
                    scope.viewReport = function () {
                        var xx = $('#report_'+scope.testSummaryData.testId).val();
                        // console.log(xx);
                        if(xx=='-1'){
                            // console.log("Please choose the report to view.");
                            $('#reportModalBody').text("Please select the report to view.");
                        }else{
                            var reportid = scope.testSummaryData.reportsID[xx];
                            console.log(reportid);
                            testService.getTestReport(reportid).then(function(report){
                                console.log(report);
                                $('#reportModalBody').text(report.content);
                            });
                        }
                    };

                    scope.init = function(){
                        return scope.updateTestSummary().then(function(){
                            testService.getTestConfiguration(scope.testId).then(function(){});

                            scope.getTemplate("listitem").then(function(response){
                                var cached_compiled, compileResult;
                                cached_compiled = _cached_templates["test_summary/listitem"];
                                if(cached_compiled != null){
                                    return cached_compiled(scope, function(clonedElem, scope){
                                        var targetElem;
                                        targetElem = $(elem);
                                        targetElem.empty();
                                        return targetElem.append(clonedElem);
                                    })
                                }else{
                                    //set response.data to the content of the elem
                                    elem.html(response.data);
                                    // compile the new DOM and link it to the current
                                    // scope.
                                    // NOTE: we only compile .childNodes so that
                                    // we don't get into infinite loop compiling ourselves
                                    // More: https://docs.angularjs.org/api/ng/service/$compile
                                    compileResult = $compile(elem.contents());
                                    _cached_templates["test_summary/listitem"] = compileResult;
                                    return compileResult(scope, function(clonedElem, scope){
                                        $(elem).empty();
                                        return $(elem).append(clonedElem);
                                    });
                                }
                            }, function(error){
                                console.warn("Could not load testsummary template: " + error);
                                testIdIdx = scope.testIds.indexOf(scope.testId);
                                return scope.testIds.splice(testIdIdx, 1);
                            });
                        });
                    };

                    return scope.init();
                }
            }
        }]);

}).call(this);